//重写compareTo方法
package daily.may0514;

import java.util.TreeSet;

class Student implements Comparable<Object> {
    private String name;
    private int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return name + ":" + age;
    }
    //重写Comparable接口的compareTo方法
    @Override
    public int compareTo(Object o) {
        //多态：向下转型
        Student stu = (Student)o;
        //定义比较方式，先比较age
        if(this.age > stu.age){
            return 1;//返回1为升序，返回-1为降序
        }
        //年龄相同则比较name
        if(0 == this.age - stu.age){
            //这里调用的是String类的compareTo方法，默认为首字母升序。
            //不要与此处重写的compareTo方法混淆。
            return this.name.compareTo(stu.name);
        }
        return -1;
    }
}
public class TreeSetCompareToOverrideTest {
    public static void main(String[] args) {
        TreeSet<Student> treeSet = new TreeSet<>();
        treeSet.add(new Student("张三",22));
        treeSet.add(new Student("李四",19));
        treeSet.add(new Student("王五",19));
        treeSet.add(new Student("赵六",21));
        treeSet.add(new Student("田七",20));
        treeSet.add(new Student("田七",18));//同名不同龄
        treeSet.add(new Student("赵六",21));//重复
        System.out.println(treeSet);
    }
}
